package com.maya.medicalwastes.ui;

import android.inputmethodservice.ExtractEditText;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.maya.medicalwastes.CollectActivity;
import com.maya.medicalwastes.ParamConstant;
import com.maya.medicalwastes.R;
import com.maya.medicalwastes.adapter.OutputAdapter;
import com.maya.medicalwastes.adapter.TadayCollectAdapter;
import com.maya.medicalwastes.adapter.OutputItemAdapter;
import com.maya.medicalwastes.dialog.SureCollectDialog;
import com.maya.medicalwastes.dialog.UploadErrorDialog;
import com.maya.medicalwastes.entity.CollectBean;
import com.maya.medicalwastes.entity.KeyBean;
import com.maya.medicalwastes.entity.WaitWareBean;
import com.maya.medicalwastes.httpNet.ApiService;
import com.maya.medicalwastes.httpNet.HttpService;
import com.maya.medicalwastes.httpNet.callback.ResponseCallBack;
import com.maya.medicalwastes.httpNet.common.SharedPreferencesConstant;
import com.maya.medicalwastes.httpNet.manage.RetrofitManager;
import com.maya.medicalwastes.httpNet.model.ResultModel;
import com.maya.medicalwastes.util.DateUtils;
import com.maya.medicalwastes.util.PrefUtils;
import com.maya.medicalwastes.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;

/**
 * @author created by fuguoyong
 * 版本：1.0
 * 创建日期：2020-11-19 15
 * 描述：CollectActivity
 */
public class OutputActivity extends AppCompatActivity {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.edit)
    ExtractEditText edit;
    @BindView(R.id.tv_ware_name)
    TextView tv_ware_name;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_companity)
    TextView tv_companity;
    @BindView(R.id.tv_warder)
    TextView tv_warder;
    @BindView(R.id.btn_one)
    Button btnOne;
    @BindView(R.id.btn_sure)
    Button btn_sure;
    @BindView(R.id.et_transportCarLicensePlate)
    EditText et_transportCarLicensePlate;
    @BindView(R.id.tv_num)
    TextView tv_num;
    @BindView(R.id.tv_sumWeight)
    TextView tv_sumWeight;
    @BindView(R.id.type)
    RecyclerView typeRecy;
    List<CollectBean> mlist = new ArrayList<>();
    List<KeyBean> keyBeans = new ArrayList<>();
    OutputAdapter collectAdapter;
    OutputItemAdapter wareItemAdapter;
    UploadErrorDialog    uploadErrorDialog;
    SureCollectDialog    sureCollectDialog;
    //仓库id
        private String id;
        private String zyrid;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_output);
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            id = bundle.getString("ID", "");
            tv_ware_name.setText(bundle.getString("warehouse", ""));
            tv_companity.setText(bundle.getString("compName", ""));
            tv_warder.setText(bundle.getString("zyr", ""));
            zyrid = bundle.getString("zyrid", "");
        }
        tv_title.setText("出库");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        collectAdapter = new OutputAdapter(R.layout.list_collect_outpu_item, mlist);
        recyclerView.setAdapter(collectAdapter);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.HORIZONTAL);
        typeRecy.setLayoutManager(manager);
        wareItemAdapter = new OutputItemAdapter(R.layout.list_item_output, keyBeans);
        typeRecy.setAdapter(wareItemAdapter);
        wareItemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_type) {
                    for (KeyBean bean : keyBeans) {
                        bean.setCheck(false);
                    }
                    keyBeans.get(position).setCheck(true);
                    wareItemAdapter.notifyDataSetChanged();

                }
            }
        });
        keySearch();
        btnOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                queryByWarehouse(id);
            }
        });
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            if (collectAdapter.getData().size()>0){
              if (!et_transportCarLicensePlate.getText().toString().equals("")){
                  sureCollectDialog = new SureCollectDialog(OutputActivity.this);
                sureCollectDialog.setOnBtnClickListener(new SureCollectDialog.OnBtnClickListener() {
                 @Override
                 public void onOkClick(String base,boolean flag) {
                if (flag){
                    updateWarehouseOut(base);
                }else {
                    ToastUtils.ViewToast(OutputActivity.this,"您还没有签名");
                    return;
                }
            }

            @Override
            public void onCancelClick() {

            }
                 });
        sureCollectDialog.popDialog();
    }else {
        ToastUtils.ViewToast(OutputActivity.this,"请输入装运车牌号");
    }
}else {
    ToastUtils.ViewToast(OutputActivity.this,"请添加出库数据");
    return;
}
            }
        });
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().contains("=") &&editable.toString().contains("LGT")) {
                    queryByTrash(editable.toString());
                }
            }
        });
        collectAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                if (view.getId()==R.id.btn_relevancy){
//                }else if (view.getId()==R.id.btn_up){
//
//                    CollectBean collectBean = (CollectBean) adapter.getData().get(position);
//
//                        uploadErrorDialog = new UploadErrorDialog(OutputActivity.this, collectBean.getGarbageId());
//                    uploadErrorDialog.setOnBtnClickListener(new UploadErrorDialog.OnBtnClickListener() {
//                        @Override
//                        public void onOkClick(String type, String string) {
//                            updateAbnormalReporting(collectBean, string);
//
//                        }
//
//                        @Override
//                        public void onCancelClick() {
//
//                        }
//                    });
//                    uploadErrorDialog.popDialog();
//
//                }
            }
        });

    }

    private void queryByTrash(String key) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("trashId", key);
        param.put(ParamConstant.TOKEN, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        Observable<ResultModel<WaitWareBean>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).queryByTrash(param);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<WaitWareBean>>() {
            @Override
            public void onResponse(ResultModel<WaitWareBean> response) {
                if (response.httpCode == 200) {
                   // collectAdapter.replaceData(response.data.getPageInfo().getList());
                    edit.setText("");
                }

            }

            @Override
            public void onFailure(int httpCode) {
                edit.setText("");
            }
        }, this);


    }
    private void queryByWarehouse(String key) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("warehouseId", key);
        param.put(ParamConstant.TOKEN, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        Observable<ResultModel<WaitWareBean>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).queryByWarehouse(param);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<WaitWareBean>>() {
            @Override
            public void onResponse(ResultModel<WaitWareBean> response) {
                if (response.httpCode == 200) {
                    if (response.data.getList().size()>0){
                        mlist.addAll(response.data.getList());
                        collectAdapter.replaceData(response.data.getList());
                        tv_sumWeight.setText(response.data.summary.getSumWeight()+"kg");
                        tv_num.setText(response.data.summary.getNum()+"件");
                    }else {
                        ToastUtils.ViewToast(OutputActivity.this,"暂无可出库垃圾");
                    }

                }

            }

            @Override
            public void onFailure(int httpCode) {
            }
        }, this);
    }
    private void updateWarehouseOut(String pic) {
        String s = et_transportCarLicensePlate.getText().toString();
        HashMap<String, Object> param = new HashMap<>();
        param.put("transportPeopleId", zyrid);
        param.put("transportPeopleName", tv_warder.getText().toString());
        param.put("transportCarLicensePlate",s );
        param.put("warehouseOutPicture", pic);
        param.put("garbageIds", mlist);
        Observable<ResultModel<String>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).updateWarehouseOut(param,PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<String>>() {
            @Override
            public void onResponse(ResultModel<String> response) {
                if (response.httpCode == 200) {
                    mlist.clear();
                    collectAdapter.notifyDataSetChanged();
                    ToastUtils.ViewToast(OutputActivity.this,"出库成功");
                    tv_sumWeight.setText("0kg");
                    tv_num.setText("0件");
                }

            }

            @Override
            public void onFailure(int httpCode) {

            }
        }, this);
    }
    public void keySearch() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("key", "CATEGORY");
        param.put(ParamConstant.TOKEN, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        Observable<ResultModel<ArrayList<KeyBean>>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).Keyword(param);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<ArrayList<KeyBean>>>() {
            @Override
            public void onResponse(ResultModel<ArrayList<KeyBean>> response) {
                if (response != null && response.httpCode == 200) {
                    response.data.add(0, new KeyBean("", "全部", true));
//                    keyBeans.addAll(response.data);
                    wareItemAdapter.replaceData(response.data);

                }
            }
            @Override
            public void onFailure(int httpCode) {
            }
        }, this);


    }

    private void updateAbnormalReporting(CollectBean collectBean, String string) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("garbageId", collectBean.getGarbageId());
        param.put("abnormalInfo", string);
        param.put("reportPerson", PrefUtils.getString(OutputActivity.this, "authOrgId", ""));
        param.put("abnormalDictionary", collectBean.getGarbageCategory());
        Observable<ResultModel<WaitWareBean>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).waitWarehousingList(param, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<WaitWareBean>>() {
            @Override
            public void onResponse(ResultModel<WaitWareBean> response) {
                if (response.httpCode == 200) {
                    ToastUtils.ViewToast(OutputActivity.this, "异常上报成功");
                } else {
                    ToastUtils.ViewToast(OutputActivity.this, "异常上报失败");

                }
                uploadErrorDialog.dismiss();
            }

            @Override
            public void onFailure(int httpCode) {
            }
        }, this);


    }




}
